import React, { useState, useRef } from 'react';
import { Button, Tag, Tooltip, Space, Card, Descriptions, Modal, message } from 'antd';
import { 
  KeyOutlined, 
  ReloadOutlined, 
  FilterOutlined,
  SearchOutlined,
  SortAscendingOutlined
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { PermissionList, PaginatedPermissionListList } from '@/services/generated/src/index';

interface EnhancedPermissionsListProps {
  groupId: number;
  groupName: string;
  visible: boolean;
  onClose: () => void;
}

const EnhancedPermissionsList: React.FC<EnhancedPermissionsListProps> = ({
  groupId,
  groupName,
  visible,
  onClose,
}) => {
  const actionRef = useRef<ActionType>();
  const [selectedPermission, setSelectedPermission] = useState<PermissionList | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);

  // 查看权限详情
  const handleViewDetail = (record: PermissionList) => {
    setSelectedPermission(record);
    setDetailModalVisible(true);
  };

  // 表格列定义 - 充分利用后端配置式Action的功能
  const columns: ProColumns<PermissionList>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
      sorter: true,
    },
    {
      title: '权限名称',
      dataIndex: 'name',
      width: 200,
      copyable: true,
      ellipsis: true,
      // 🔑 关键：利用后端的搜索功能
      tooltip: '支持模糊搜索',
    },
    {
      title: '权限代码',
      dataIndex: 'codename',
      width: 150,
      copyable: true,
      // 🔑 关键：利用后端的过滤功能
      tooltip: '支持精确匹配和包含匹配',
    },
    {
      title: '应用标签',
      dataIndex: 'content_type_app_label',
      width: 120,
      valueType: 'select',
      // 🔑 关键：利用后端的自定义参数映射
      fieldProps: {
        placeholder: '选择应用',
      },
      valueEnum: {
        'auth': { text: 'Auth', status: 'Processing' },
        'permissions': { text: 'Permissions', status: 'Success' },
        'contenttypes': { text: 'ContentTypes', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color="blue">{record.content_type_app_label}</Tag>
      ),
    },
    {
      title: '模型名称',
      dataIndex: 'content_type_model',
      width: 120,
      valueType: 'select',
      valueEnum: {
        'user': { text: 'User', status: 'Processing' },
        'group': { text: 'Group', status: 'Success' },
        'permission': { text: 'Permission', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color="green">{record.content_type_model}</Tag>
      ),
    },
    {
      title: '内容类型ID',
      dataIndex: 'content_type_id',
      width: 100,
      search: false,
      sorter: true,
      render: (_, record) => (
        <Tag>{record.content_type_id}</Tag>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (_, record) => [
        <Tooltip key="detail" title="查看详情">
          <Button
            type="link"
            size="small"
            icon={<KeyOutlined />}
            onClick={() => handleViewDetail(record)}
          />
        </Tooltip>,
      ],
    },
  ];

  return (
    <>
      <Modal
        title={
          <Space>
            <KeyOutlined />
            <span>组权限列表 - {groupName}</span>
            <Tag color="blue">配置式Action</Tag>
          </Space>
        }
        open={visible}
        onCancel={onClose}
        footer={[
          <Button key="close" onClick={onClose}>
            关闭
          </Button>
        ]}
        width={1200}
        style={{ top: 20 }}
      >
        <Card size="small" style={{ marginBottom: 16 }}>
          <Descriptions size="small" column={3}>
            <Descriptions.Item label="功能特性">
              <Space>
                <Tag icon={<SearchOutlined />} color="processing">搜索</Tag>
                <Tag icon={<FilterOutlined />} color="success">过滤</Tag>
                <Tag icon={<SortAscendingOutlined />} color="warning">排序</Tag>
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="支持的查询">
              精确匹配、包含匹配、多值匹配
            </Descriptions.Item>
            <Descriptions.Item label="自定义参数">
              app_label、content_type映射
            </Descriptions.Item>
          </Descriptions>
        </Card>

        <ProTable<PermissionList>
          columns={columns}
          actionRef={actionRef}
          request={async (params, sort) => {
            try {
              await autoLoginInDev();

              // 🔑 关键：充分利用后端配置式Action的所有功能
              const requestParams: any = {
                id: groupId,
                page: params.current || 1,
                pageSize: params.pageSize || 20,
              };

              // 搜索功能 - 后端支持 name, codename, content_type__model
              if (params.name) {
                requestParams.search = params.name;
              }

              // 过滤功能 - 利用ViewSet完整字典格式
              if (params.codename) {
                requestParams.codename = params.codename;
              }
              if (params.content_type_app_label) {
                requestParams.appLabel = params.content_type_app_label; // 自定义参数映射
              }
              if (params.content_type_model) {
                requestParams.contentType__model = params.content_type_model;
              }

              // 排序功能 - 后端支持多字段排序
              if (sort && Object.keys(sort).length > 0) {
                const sortFields = Object.entries(sort)
                  .map(([field, order]) => order === 'descend' ? `-${field}` : field);
                requestParams.ordering = sortFields.join(',');
              }

              console.log('🚀 配置式Action请求参数:', requestParams);

              const response = await apiClients.permissions.permissionsGroupsPermissionsList(requestParams);

              console.log('🎯 配置式Action响应:', response);

              // 处理分页响应
              const responseData = (response as any).data || response;
              return {
                data: responseData?.items || [],
                success: true,
                total: responseData?.total || 0,
              };
            } catch (error) {
              console.error('获取组权限列表失败:', error);
              message.error('获取组权限列表失败');
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
            defaultCollapsed: false,
            searchText: '搜索',
            resetText: '重置',
            collapseRender: (collapsed) => (
              <Space>
                <FilterOutlined />
                {collapsed ? '展开筛选' : '收起筛选'}
              </Space>
            ),
          }}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
          }}
          dateFormatter="string"
          headerTitle={
            <Space>
              <KeyOutlined />
              <span>配置式权限列表</span>
              <Tag color="processing">支持搜索、过滤、排序</Tag>
            </Space>
          }
          toolBarRender={() => [
            <Button
              key="refresh"
              icon={<ReloadOutlined />}
              onClick={() => actionRef.current?.reload()}
            >
              刷新
            </Button>,
          ]}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          scroll={{ y: 400 }}
        />
      </Modal>

      {/* 权限详情Modal */}
      <Modal
        title={`权限详情 - ${selectedPermission?.name}`}
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setSelectedPermission(null);
        }}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedPermission && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="权限ID">
              {selectedPermission.id}
            </Descriptions.Item>
            <Descriptions.Item label="权限名称">
              {selectedPermission.name}
            </Descriptions.Item>
            <Descriptions.Item label="权限代码">
              <Tag color="blue">{selectedPermission.codename}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="应用标签">
              <Tag color="green">{selectedPermission.content_type_app_label}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="模型名称">
              <Tag color="orange">{selectedPermission.content_type_model}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="内容类型ID">
              {selectedPermission.content_type_id}
            </Descriptions.Item>
            <Descriptions.Item label="内容类型名称">
              {selectedPermission.content_type_name}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </>
  );
};

export default EnhancedPermissionsList;
